package com.example.bootweb.security;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.UUID;

@Slf4j
@Component
public class SuccessHandler implements AuthenticationSuccessHandler {


    @Value("${server.port}")
    String port;

    @Autowired
    private StringRedisTemplate StringRedisTemplate;

    final String cookieName = "token";

    final String tokenPrefix = "token:";

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        String uuid = UUID.randomUUID().toString();
        //认证成功，存token到redis
        StringRedisTemplate.opsForValue().set(tokenPrefix+uuid,"admin");
        //写入cookie
        Cookie cookie = new Cookie(cookieName, uuid);
        response.addCookie(cookie);

        log.info("认证成功"+port+"    "+uuid);
        response.sendRedirect("/");
    }

}
